import type { Graph, Cell, Model } from "@antv/x6";
import store from "@/store";
import { settingMap, WIDGET_PREFIX } from "@/components/x6/register";
import type { WidgetItem } from "@/store/module/widget";

export function useGraphEvent(graph: Graph) {
  bindAdd(graph)
  bindMove(graph);
  bindMoving(graph);
  bindMoveEnd(graph);
  bindSelect(graph);

  function bindAdd(instance: Graph) {
    instance.on('node:added', ({ node }) => {
      const { x, y } = node.position()
      const bindData = node.data.sideConfig
      // const widgetStore = useWidgetStoreOutSide()
      const settingInstance = settingMap[`${WIDGET_PREFIX}${bindData.type}`]
      const itemSettings = settingInstance.initSettings()
      // widgetStore.addWidget(draggingNode.id, itemSettings)
      const widgetItem: WidgetItem = {
        width: itemSettings.width,
        height: itemSettings.height,
        name: itemSettings.name,
        x,
        y
      }
      store.commit('setWidget', {
        id: node.id,
        item: widgetItem
      })
    })
  }
  function bindMove(instance: Graph) {
    instance.on("node:move", ({ x, y, node }: any) => {
    });
  }
  function bindMoving(instance: Graph) {
    instance.on("node:moving", ({ x, y, node }: any) => {
    });
  }
  function bindMoveEnd(instance: Graph) {
    instance.on("node:moved", ({ x, y, node }: any) => {
      store.commit('updateWidgetXY', {id: node.id, position: { x, y }})
    });
  }
  function bindSelect(instance: Graph) {
    instance.on(
      "cell:selected",
      (args: { cell: Cell; options: Model.SetOptions }) => {
        // code here
        console.log("被选中");
      }
    );
  }
}
